package com.dongwu.manager.api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.dongwu.manager.service.UserInfoService;
import com.gexin.fastjson.JSON;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dongwu.common.constants.TencentIMConstants;
import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.HttpClientUtils;
import com.dongwu.config.IMSpliceUrl;
import com.dongwu.config.tencentIMGetSig;
import com.dongwu.manager.entity.Device;
import com.dongwu.manager.service.DeviceService;
import com.dongwu.manager.service.SettingService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping("/IMapi")
public class IMApiController {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource
	private SettingService settingService;

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private DeviceService deviceService;

	/**
	 * 获取设备IM账号
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getUserSig", method = RequestMethod.POST)
	@ApiOperation(value = TencentIMConstants.GETIMLOGIN)
	@ResponseBody
	public Result getUserSig(
			@ApiParam(value = TencentIMConstants.MACADDR_ONE, required = true) @RequestParam(value = "macAddr", required = true) String macAddr) {
		String userSig = "";
		Map<String, Object> mapTypes = null;
		// 封装json
		JSONObject jsonParams = new JSONObject();
		jsonParams.put("Identifier", macAddr);
		// jsonParams.put("Nick", macAddr);
		// jsonParams.put("FaceUrl", "www.baidu.com");

		try {
			// 获取用户sig
			userSig = tencentIMGetSig.GetSig(macAddr);
			if (settingService.findAll().size() == 0) {
				return Result.errorResult("设置默认IM配置！");
			}
			// 拼接出完整url
			String rootUrl = IMSpliceUrl.Url(TencentIMConstants.ACCOUNT_IMPORT,
					tencentIMGetSig.GetSig(settingService.findAll().get(0).getRoot()));

			// 执行请求腾讯服务器注册账号并返回处理信息
			// json = IMHttpClient.PostTencent(rootUrl, jsonParams);
			mapTypes = HttpClientUtils.PostJsonObjResMap(rootUrl, jsonParams);
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (mapTypes.get("ActionStatus").toString().equals("OK")) {

			mapTypes.remove("ErrorInfo");
			mapTypes.remove("ErrorCode");
			mapTypes.put("userSig", userSig);

			return Result.successResult(mapTypes);
		} else {

			return Result.errorResult("请求失败！");
		}
	}

//	/**
//	 * 获取用户在线状态
//	 *
//	 * @return
//	 */
//	@RequestMapping(value = "/getUserState", method = RequestMethod.POST)
//	@ApiOperation(value = TencentIMConstants.UPDATE_USER_STATE)
//	@ResponseBody
//	public Result getUserState(
//			@ApiParam(value = TencentIMConstants.MACADDR_ONE, required = true) @RequestParam("macAddr") String macAddr,
//			@ApiParam(value = TencentIMConstants.USER_STATE, required = true) @RequestParam("status") Integer status) {
//		try {
//			Device dev = deviceService.findBySn(macAddr);
//			if (status == 0) {
//				dev.setIMStatus(Device.iMStatusType.Online);
//			} else {
//				dev.setIMStatus(Device.iMStatusType.PushOnline);
//			}
//			deviceService.update(dev);
//		} catch (Exception e) {
//			log.info(e.getMessage());
//			e.printStackTrace();
//		}
//		return Result.successResult();
//	}
	
	/**
	 * IM登录事件回调url
	 *
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value = "/IMCallback", method = RequestMethod.POST)
	@ResponseBody
	public Result IMCallback(String SdkAppid,String CallbackCommand,String contenttype,String ClientIP,String OptPlatform,@RequestBody String info) {
		Map<String, Object> resmap= new HashMap<>();
		Map<String, Object>  map = JSON.parseObject(info);
		if(SdkAppid.equals(TencentIMConstants.SDKAPPID) || map.get("CallbackCommand").toString().equals("State.StateChange")){
			//map.get("Reason");//产生回调事件的原因
			@SuppressWarnings("unchecked")
			Map<String, Object> Mapinfo =  (Map<String, Object>) map.get("Info");
			if(!Mapinfo.get("To_Account").toString().equals("admin")){
				try {
					Device dev = deviceService.findBySn(Mapinfo.get("To_Account").toString());
					if(Mapinfo.get("Action").toString().equals("Login") ){
						dev.setIMStatus(Device.iMStatusType.Online);
					}
					if(Mapinfo.get("Action").toString().equals("Logout") ){
						dev.setIMStatus(Device.iMStatusType.PushOnline);
					}
					deviceService.update(dev);
				} catch (Exception e) {
					e.printStackTrace();
					log.info(e.getMessage());
				}
			}
			resmap.put("ActionStatus", "OK");
			resmap.put("ErrorCode", 0);
			resmap.put("ErrorInfo", "");
		}else{
			resmap.put("ActionStatus", "FAIL");
			resmap.put("ErrorCode", 1);
			resmap.put("ErrorInfo", "appid不匹配或者不是状态改变类型的消息");
		}
		return Result.successResult(resmap);
	}
	// /**
	// * 获取用户在线状态
	// *
	// * @return
	// */
	// @RequestMapping(value = "/getUserState", method = RequestMethod.POST)
	// @ApiOperation(value = TencentIMConstants.MACADDR_STATE)
	// public Result getUserState(
	// @ApiParam(value = TencentIMConstants.MACADDR_LIST, required = true)
	// @RequestBody Map<String, Object> macAddrMap) {
	// String json = "";
	// try {
	// // 拼接出完整url
	// String rootUrl = IMHttpClient.Url(TencentIMConstants.QUEERYSTATE,
	// tencentIMGetSig.GetSig(settingService.findAll().get(0).getRoot()));
	//
	// // 封装json
	// JSONObject jsonParams = new JSONObject();
	// jsonParams.put("To_Account", macAddrMap.get("To_Account"));
	//
	// // 执行请求腾讯服务器注册账号并返回处理信息
	// json = IMHttpClient.PostTencent(rootUrl, jsonParams);
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// Map<String, Object> mapTypes = JSON.parseObject(json);
	// if (mapTypes.get("ActionStatus").equals("OK")) {
	// mapTypes.remove("ErrorInfo");
	// mapTypes.remove("ErrorCode");
	// return Result.successResult(mapTypes);
	// } else {
	//
	// return Result.errorResult("请求失败！");
	// }
	// }
	/**
	 * 微信授权请求重定向至微信授权
	 * 
	 * @param req
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value = "/WeiXinRedirectUrl", method = RequestMethod.GET)
	public String redirectUrl(HttpServletRequest req) {
		// 获取请求地址
		String url = req.getScheme() + "://" + req.getServerName() + TencentIMConstants.WEIXINOAUTHREDIRECTAPI;
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.err.println(url);
		StringBuffer sb = new StringBuffer();
		sb.append(TencentIMConstants.WEIXINOAUTHGETCODEURL);
		sb.append("?appid=" + TencentIMConstants.WEIXINAPPID);
		sb.append("&redirect_uri=" + url);
		sb.append("&response_type=code");
		sb.append("&scope=snsapi_userinfo");// snsapi_base,snsapi_userinfo
		sb.append("&state=authorization_code");
		sb.append("#wechat_redirect");
		return "redirect:" + sb;
	}

	/**
	 * 微信网页授权页面
	 */
	@ApiIgnore
	@RequestMapping(value = "/getAuthorizationPage", method = RequestMethod.POST)
	public String getAuthorizationPage(Model model, String code) {
		Map<String, Object> grs = null;
		StringBuffer sb = new StringBuffer();
		sb.append(TencentIMConstants.WEIXINOAUTHGETTOKENURL);
		sb.append("?appid=" + TencentIMConstants.WEIXINAPPID);
		sb.append("&secret=" + TencentIMConstants.WEIXINSECRET);
		sb.append("&code=" + code);
		sb.append("&grant_type=authorization_code");
		try {
			grs = HttpClientUtils.HttpGetResMap(sb.toString());
			String url = TencentIMConstants.GETUSERINFO.replace("ACCESS_TOKEN", grs.get("access_token").toString())
					.replace("OPENID", grs.get("openid").toString());
			Map<String, Object> userInfoMap = HttpClientUtils.HttpGetResMap(url);
			userInfoService.saveUserInfo(userInfoMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 获取第二步的refresh_token后，请求以下链接获取access_token：
		// https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
		// String refresh_token = grs.get("refresh_token").toString();

		model.addAttribute("openid", grs.get("openid"));

		return "manager/WeiXinAuthorization";
	}
}
